package com.atguigu.edu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.app.BaseApp;
import com.atguigu.edu.bean.TrafficHomeDetailPageViewBean;
import com.atguigu.edu.common.Constant;
import com.atguigu.edu.util.AtguiguUtil;
import com.atguigu.edu.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsTrafficPageViewHomeAndGoodDetailWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTrafficPageViewHomeAndGoodDetailWindow().init(4003,2,
                "DwsTrafficPageViewHomeAndGoodDetailWindow",
                Constant.TOPIC_DWD_TRAFFIC_PAGE);
    }
    @Override
    public void handle(StreamExecutionEnvironment ev, DataStreamSource<String> stream) {
        //过滤详细页和首页
        SingleOutputStreamOperator<JSONObject> homeAndGoodDetailStream = filterHomeAndGoodDetail(stream);
        //封装为pojo
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream = parseToPojo(homeAndGoodDetailStream);
       //开窗聚合
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream = windowAndAgg(beanStream);
        //写到clickhouse
        writeToClickhouse(resultStream);
    }

    private void writeToClickhouse(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_page_view_window",TrafficHomeDetailPageViewBean.class));
    }

    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream) {
        return beanStream.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean value1, TrafficHomeDetailPageViewBean value2) throws Exception {
                        value1.setHomeUvCt(value1.getHomeUvCt() + value2.getHomeUvCt());
                        value1.setGoodDetailUvCt(value1.getGoodDetailUvCt() + value2.getGoodDetailUvCt());
                        //重新设置处理时间
                        value1.setTs(System.currentTimeMillis());
                        return value1;
                    }
                }, new ProcessAllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void process(Context context,
                                        Iterable<TrafficHomeDetailPageViewBean> iterable,
                                        Collector<TrafficHomeDetailPageViewBean> collector) throws Exception {
                        TrafficHomeDetailPageViewBean bean = iterable.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(context.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(context.window().getEnd()));
                        collector.collect(bean);
                    }
                });
    }

    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> parseToPojo(SingleOutputStreamOperator<JSONObject> stream) {
        return stream.keyBy(obj-> obj.getString("mid"))
                .process(new KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>() {
                    private ValueState<String> homeLastVisitDateState;
                    private ValueState<String> goodDetailLastVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        homeLastVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("home", String.class));
                        goodDetailLastVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("goodDetail", String.class));
                    }
                    @Override
                    public void processElement(JSONObject jsonObject,
                                               Context context,
                                               Collector<TrafficHomeDetailPageViewBean> collector) throws Exception {
                        String pageId = jsonObject.getString("page_id");
                        Long ts = jsonObject.getLong("ts");
                        String today = AtguiguUtil.tsToDate(ts);
                        Long homeUvCt = 0l;
                        Long goodDetailUvCt = 0l;
                        if ("home".equals(pageId)){
                            if (!today.equals(homeLastVisitDateState.value())){
                                homeUvCt=1l;
                                homeLastVisitDateState.update(today);
                            }
                        }else {
                            if (!today.equals(goodDetailLastVisitDateState.value())){
                                goodDetailUvCt=1l;
                                goodDetailLastVisitDateState.update(today);
                            }
                        }
                        if (homeUvCt+goodDetailUvCt==1){
                            collector.collect(new TrafficHomeDetailPageViewBean("","",
                                    homeUvCt,goodDetailUvCt,ts));
                        }
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> filterHomeAndGoodDetail(DataStreamSource<String> stream) {
       return stream.map(JSON::parseObject)
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((obj,ts)-> obj.getLong("ts"))
                        .withIdleness(Duration.ofSeconds(60)))
                .filter(obj -> {return "home".equals(obj.getString("page_id"))
                || "course_detail".equals(obj.getString("page_id"));}
                );
    }
}